package com.zjq.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;
import java.util.Map;

/**
 * @author zjq
 * @date 2020/3/17 10:37
 * <p>title:jwt工具类</p>
 * <p>company:zjhcsoft</p>
 * <p>description:</p>
 */
@ConfigurationProperties(value = "jwt.config")
@Getter
@Setter
public class JwtUtil {

    private String key;

    private long ttl;

    /**
     * 签发 token
     * @param id
     * @param subject
     * @param map
     * @return
     */
    public String createJWT(String id, String subject, Map<String,Object> map){
        long now = System.currentTimeMillis();
        long exp = now+ttl;
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setSubject(subject).setIssuedAt(new Date(now))
                .signWith(SignatureAlgorithm.HS256,key);
        for(Map.Entry<String,Object> entry:map.entrySet()){
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }
        if(ttl>0){
            jwtBuilder.setExpiration(new Date(exp));
        }
        String token = jwtBuilder.compact();
        return token;

    }


    /**
     * 解析jwt
     * @param token
     * @return
     */
    public Claims parseJwt(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token).getBody();
        }catch (Exception e){

        }
        return claims;
    }
}
